#include <QWidget>
#include <QtDebug>

#include "SpaceExpWidget.h"
using namespace std;

SpaceExpWidget::SpaceExpWidget(QWidget *parent) : QWidget(parent) {

    qDebug()<<"SpaceExpWidget:SpaceExpWidget(): Initializing device";

    if(spnav_open()==-1)
    {
        spnav_open();
         qDebug()<<"SpaceExpWidget:SpaceExpWidget():failed to connect to the space navigator daemon\n";
    }

    qDebug()<<"SpaceExpWidget:SpaceExpWidget(): Initializing done ...";
}


SpaceExpWidget::~SpaceExpWidget()
{
    close();
}

int SpaceExpWidget::open()
{
    if(spnav_open()==-1)
    {
         spnav_open();
         qDebug()<<"SpaceExpWidget:SpaceExpWidget():failed to connect to the space navigator daemon\n";
         return -1;
    }
    else
        return 1;
}

void SpaceExpWidget::close()
{
    spnav_close();
}

void SpaceExpWidget::pollDevice()
{
        int k=0;
        dEvent.type = 4;
         k = spnav_poll_event(&dEvent);

         x = 0;
         y = 0;
         z = 0;
         //qDebug()<<"SpaceExpWidget::pollDevice()"<<dEvent.type;

         if(dEvent.type == SPNAV_EVENT_MOTION) {

            // SpaceExplorer mapping
            // Y axis points inward for the device
            // Z axis points downward for the device

            //qDebug()<<"got motion event: t"<< dEvent.motion.x<< dEvent.motion.y<< dEvent.motion.z;


            if((((abs(dEvent.motion.x-x)<15) & (abs(dEvent.motion.z-y)<15)) & (abs(dEvent.motion.x)<15 & abs(dEvent.motion.z)<15))) {
                // resetting device position if there is no input from the device


            } else {
                x = dEvent.motion.x;
                y = dEvent.motion.z;
                z = dEvent.motion.y;

                rx = dEvent.motion.rx;
                ry = dEvent.motion.ry;
                rz = dEvent.motion.rz;

            }
        } else {

            if(dEvent.button.press) {
                button = dEvent.button.bnum;
            } else {
                button = -1;
                x = 0;
                y = 0;
                z = 0;
            }
            //qDebug()<<"got button event"<<button;


        }
}
